package moni.anyou.com.view.view;

import android.Manifest;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

//import com.huawei.android.pushagent.PushManager;
import com.meizu.cloud.pushsdk.util.MzSystemUtils;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMLogLevel;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.qcloud.presentation.business.InitBusiness;
import com.tencent.qcloud.presentation.business.LoginBusiness;
import com.tencent.qcloud.presentation.event.FriendshipEvent;
import com.tencent.qcloud.presentation.event.GroupEvent;
import com.tencent.qcloud.presentation.event.MessageEvent;
import com.tencent.qcloud.presentation.event.RefreshEvent;
import com.tencent.qcloud.presentation.presenter.SplashPresenter;
import com.tencent.qcloud.presentation.viewfeatures.SplashView;
import com.tencent.qcloud.sdk.Constant;
import com.tencent.qcloud.timchat.R;
import com.tencent.qcloud.timchat.model.GroupInfo;
import com.tencent.qcloud.timchat.model.ProfileSummary;
import com.tencent.qcloud.timchat.model.UserInfo;
import com.tencent.qcloud.timchat.ui.ChatActivity;
import com.tencent.qcloud.timchat.ui.customview.DialogActivity;
import com.tencent.qcloud.timchat.utils.PushUtil;
import com.tencent.qcloud.tlslibrary.service.TLSService;
import com.tencent.qcloud.tlslibrary.service.TlsBusiness;
import com.tencent.qcloud.ui.NotifyDialog;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.ArrayList;
import java.util.List;

import io.agora.openlive.activities.MainActivity;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.tim.TimSplashStart;
import moni.anyou.com.view.view.my.RouteTeamActivity;
import tencent.tls.platform.TLSErrInfo;
import tencent.tls.platform.TLSPwdLoginListener;
import tencent.tls.platform.TLSUserInfo;

public class SplashActivity extends FragmentActivity implements SplashView,TIMCallBack {

    SplashPresenter presenter;
    private int LOGIN_RESULT_CODE = 100;
    private int GOOGLE_PLAY_RESULT_CODE = 200;
    private final int REQUEST_PHONE_PERMISSIONS = 0;
    private static final String TAG = "mytim";
    private TimSplashStart timSplashStart;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(TAG,"IS SDK START:version="+TIMManager.getInstance().getVersion());

        clearNotification();
        timSplashStart=new TimSplashStart(this);
        timSplashStart.onCreate(this);



    }

    String id="313";
    final String userSig="eJxNjl1vgjAYhf9Lb11mP0FMduFAM*1cNH5dNgyKK07EtjDQ7L8PUZKdy*fJ*55zBev31XMYRacis8LWuQRDAMHTHee5ikVoBdHxPyyrXGkpwsRK3WDEGMMQdlbFMrMqUa0jiDywiQ*i-Xe7oBAiF1LmdVLtGzwfb-zp26FwqF9t*uVlFeBtWlZHs10uBuuZW9RF5FxQQqe75e5DD0ZqPELcK-ef-dTnhn*fJ*kiIDjhZzz7*aonqDd3UJBy3sPBq3l5lFl1lO1s6rqIEa8bXkpt1ClrFIaIIUzgLeD3DwnoVWc_";


    /**
     * 跳转到主界面
     */
    @Override
    public void navToHome() {

        Log.d("mytim", "navToHome");
        LoginBusiness.loginIm(UserInfo.getInstance().getId(), UserInfo.getInstance().getUserSig(), new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                Log.d("mytim", "*onerror:"+i+"  "+s);
            }

            @Override
            public void onSuccess() {
//
                initChat();
//                Log.d("mytim", "*onSuccess");
               // Intent intent=new Intent(SplashActivity.this,StartActivity.class);
               // intent.putExtra("identify","Team_16");
              //  intent.putExtra("type", TIMConversationType.Group);
              //  startActivity(intent);

            }
        });
    }

    private void initChat() {
        Log.d("mytim", "initChat");
        TIMUserConfig userConfig = new TIMUserConfig();
        userConfig.setUserStatusListener(new TIMUserStatusListener() {
            @Override
            public void onForceOffline() {
                Log.d(TAG, "receive force offline message");
                Intent intent = new Intent(SplashActivity.this, DialogActivity.class);
                startActivity(intent);
            }

            @Override
            public void onUserSigExpired() {
                //票据过期，需要重新登录
                new NotifyDialog().show(getString(R.string.tls_expire), getSupportFragmentManager(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //                            logout();
                    }
                });
            }
        })
                .setConnectionListener(new TIMConnListener() {
                    @Override
                    public void onConnected() {
                       System.out.println("onConnected=====================");
                    }

                    @Override
                    public void onDisconnected(int code, String desc) {
                        System.out.println("onDisconnected====================");
                    }

                    @Override
                    public void onWifiNeedAuth(String name) {
                        System.out.println("onWifiNeedAuth==============");
                    }
                });

        //设置刷新监听
        RefreshEvent.getInstance().init(userConfig);
        userConfig = FriendshipEvent.getInstance().init(userConfig);
        userConfig = GroupEvent.getInstance().init(userConfig);
        userConfig = MessageEvent.getInstance().init(userConfig);
        TIMManager.getInstance().setUserConfig(userConfig);
    }

    /**
     * 跳转到登录界面
     */
    @Override
    public void navToLogin() {

       Intent intent=new Intent(SplashActivity.this,ChatActivity.class);
                    intent.putExtra("identify","Team_16");
                    intent.putExtra("type", TIMConversationType.Group);
       startActivity(intent);
    }

    /**
     * 是否已有用户登录
     */
    @Override
    public boolean isUserLogin() {
        Log.d(TAG,""+UserInfo.getInstance().getId());
//        boolean isLogin= UserInfo.getInstance().getId()!= null && (!TLSService.getInstance().needLogin(UserInfo.getInstance().getId()));
        boolean isLogin= id!=null&&userSig!=null;
        Log.d(TAG,"isLogin:"+isLogin);
        return isLogin;
    }

    /**
     * imsdk登录失败后回调
     */
    @Override
    public void onError(int i, String s) {
        Log.e(TAG, "login error : code " + i + " " + s);
        switch (i) {
            case 6208:
                //离线状态下被其他终端踢下线
                NotifyDialog dialog = new NotifyDialog();
                dialog.show(getString(R.string.kick_logout), getSupportFragmentManager(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        navToHome();
                    }
                });
                break;
            case 6200:
                Toast.makeText(this,getString(R.string.login_error_timeout),Toast.LENGTH_SHORT).show();
                navToLogin();
                break;
            default:
                Toast.makeText(this,getString(R.string.login_error),Toast.LENGTH_SHORT).show();
                navToLogin();
                break;
        }

    }

    /**
     * imsdk登录成功后回调
     */
    @Override
    public void onSuccess() {

        Log.d(TAG,"onSuccess()");
        //初始化程序后台后消息推送
        PushUtil.getInstance();
        //初始化消息监听
        MessageEvent.getInstance();
        String deviceMan = Build.MANUFACTURER;
        //注册小米和华为推送
        if (deviceMan.equals("Xiaomi") && shouldMiInit()){
            MiPushClient.registerPush(getApplicationContext(), "2882303761517480335", "5411748055335");
        }else if (deviceMan.equals("HUAWEI")){
//            PushManager.requestToken(this);
        }

        //魅族推送只适用于Flyme系统,因此可以先行判断是否为魅族机型，再进行订阅，避免在其他机型上出现兼容性问题
        if(MzSystemUtils.isBrandMeizu(getApplicationContext())){
            com.meizu.cloud.pushsdk.PushManager.register(this, "112662", "3aaf89f8e13f43d2a4f97a703c6f65b3");
        }



        Log.d(TAG, "imsdk env " + TIMManager.getInstance().getEnv());
        initChat();
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult code:" + requestCode);
        if (LOGIN_RESULT_CODE == requestCode) {
            Log.d(TAG, "login error no " + TLSService.getInstance().getLastErrno());
            if (0 == TLSService.getInstance().getLastErrno()){
                String id = TLSService.getInstance().getLastUserIdentifier();
                UserInfo.getInstance().setId(id);
                UserInfo.getInstance().setUserSig(TLSService.getInstance().getUserSig(id));
                navToHome();
            } else if (resultCode == RESULT_CANCELED){
                finish();
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PHONE_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    init();
                } else {
                    Toast.makeText(this, getString(R.string.need_permission),Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private void init(){
        SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
        int loglvl = pref.getInt("loglvl", TIMLogLevel.DEBUG.ordinal());
        //初始化IMSDK
        InitBusiness.start(getApplicationContext(),loglvl);
        //初始化TLS
        TlsBusiness.init(getApplicationContext());

        Log.d(TAG,"init-> config "+ Constant.ACCOUNT_TYPE+"  "+Constant.SDK_APPID);
        Log.d(TAG,"init->"+id+" "+userSig);
//        Log.d(TAG,"init-> uid===>"+SysConfig.uid);
        UserInfo.getInstance().setId(id);
        UserInfo.getInstance().setUserSig(userSig);
        presenter = new SplashPresenter(this);
        presenter.start();
    }

    /**
     * 判断小米推送是否已经初始化
     */
    private boolean shouldMiInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 清楚所有通知栏通知
     */
    private void clearNotification(){
        NotificationManager notificationManager = (NotificationManager) this
                .getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        MiPushClient.clearNotification(getApplicationContext());
    }
}
